﻿#include "BaseManager.h"
#include <memory>
#include <QDialog>
#include <QEventLoop>

BaseManager::BaseManager(QObject *parent) : QObject(parent)
{
}

void BaseManager::InitConfig()
{
    QString managerName=ManagerName();
    JsonUtils::LoadJsonObject(managerName,_obj);
    InitImpl(_obj);
}

void BaseManager::InitImpl(QJsonObject obj)
{
    QString managerName=ManagerName();
    for(auto key:obj.keys())
    {
        QJsonObject value=obj[key].toObject();
        if(_factory==nullptr)
        {
            throw QString("%1 未配置 工厂实例").arg(managerName);
        }
        BaseItem *baseItem=_factory->CreateInstance(value["Type"].toString());
        baseItem->setParent(this);
        baseItem->setName(key);
        baseItem->setConfig(value);
        baseItem->setOtherConfig(value["OtherConfig"].toObject());
        qDebug()<<baseItem->name()<<"Init "<<baseItem->init();
        _allItems.append(baseItem);
    }
    qDebug()<<managerName<<__LINE__<<ManagerName()<<" "<<_allItems.count()<<"Item";
    qDebug()<<"\r\n";
}

QString BaseManager::GetIconPath(QString name)
{
    QJsonObject objItem=_obj[name].toObject();
    return objItem["IconPath"].toString();
}

QString BaseManager::GetFriendlyName(QString name)
{
    QJsonObject objItem=_obj[name].toObject();
    return objItem["FriendlyName"].toString();
}

QStringList BaseManager::GetNames()
{
    QStringList ret=_obj.keys();
    return ret;
}

QWidget *BaseManager::GetConfigWidget(QString name)
{
    BaseItem *item=GetItem<BaseItem>(name);
    return item->getConfigWidget();
}

void BaseManager::SetFactory(BaseFactory *factory)
{
    _factory=factory;
}

QString BaseManager::ManagerName()
{
   return this->metaObject()->className();
}

void BaseManager::InitMenu(QMenu *menu)
{
    for(auto name:GetNames())
    {
        QAction *act=new QAction(this);
        QString friendlyName=GetFriendlyName(name);
        act->setText(friendlyName);
        QString iconPath=GetIconPath(name);
        act->setIcon(QIcon(iconPath));
        menu->addAction(act);
        connect(act,&QAction::triggered,this,[this,name,friendlyName]()
        {
            WidgetUtils::Execute(nullptr,[this,name,friendlyName](){
                BaseItem *item=GetItem<BaseItem>(name);
                QWidget* w=item->getConfigWidget();
                w->setWindowTitle(friendlyName);
                if(dynamic_cast<QDialog*>(w))
                {
                    QDialog *d=dynamic_cast<QDialog*>(w);
                    d->exec();
                    d->deleteLater();
                }
                else
                {
                    w->setAttribute(Qt::WA_DeleteOnClose);
                    w->setWindowModality(Qt::ApplicationModal);
                    w->show();
                    QEventLoop loop;
                    QObject::connect(w, &QWidget::close, &loop, &QEventLoop::quit);
                    loop.exec();
                }

            },true);
        });
    }
}

void BaseManager::WaitForEnd()
{
}


